// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#pragma once

#include <pollux/common/base/nulls.h>
#include <pollux/vector/base_vector.h>
#include <pollux/vector/selectivity_vector.h>

namespace kumo::pollux::functions {
    /// This function returns a SelectivityVector for ARRAY/MAP vectors that selects
    /// all rows corresponding to the specified rows. This flavor is intended for
    /// use with the base vectors of decoded vectors. Use `nulls` and `rowMapping`
    /// to pass in the null and index mappings from the DecodedVector.
    template<typename T>
    SelectivityVector toElementRows(
        vector_size_t size,
        const SelectivityVector &topLevelRows,
        const T *arrayBaseVector,
        const uint64_t *nulls,
        const vector_size_t *rowMapping) {
        POLLUX_CHECK(
            arrayBaseVector->encoding() == VectorEncoding::Simple::MAP ||
            arrayBaseVector->encoding() == VectorEncoding::Simple::ARRAY);

        auto rawSizes = arrayBaseVector->rawSizes();
        auto rawOffsets = arrayBaseVector->rawOffsets();
        POLLUX_DEBUG_ONLY const auto sizeRange =
                arrayBaseVector->sizes()->template asRange<vector_size_t>().end();
        POLLUX_DEBUG_ONLY const auto offsetRange =
                arrayBaseVector->offsets()->template asRange<vector_size_t>().end();

        SelectivityVector elementRows(size, false);
        topLevelRows.applyToSelected([&](vector_size_t row) {
            auto index = rowMapping ? rowMapping[row] : row;
            if (nulls && bits::isBitNull(nulls, row)) {
                return;
            }

            POLLUX_DCHECK_LE(index, sizeRange);
            POLLUX_DCHECK_LE(index, offsetRange);

            auto size = rawSizes[index];
            auto offset = rawOffsets[index];
            elementRows.setValidRange(offset, offset + size, true);
        });
        elementRows.updateBounds();
        return elementRows;
    }

    /// This function returns a SelectivityVector for ARRAY/MAP vectors that selects
    /// all rows corresponding to the specified rows.
    template<typename T>
    SelectivityVector toElementRows(
        vector_size_t size,
        const SelectivityVector &topLevelRows,
        const T *arrayBaseVector) {
        return toElementRows(
            size,
            topLevelRows,
            arrayBaseVector,
            arrayBaseVector->raw_nulls(),
            nullptr);
    }

    /// Returns a buffer of vector_size_t that represents the mapping from
    /// topLevelRows's element rows to its top-level rows. For example, suppose
    /// `result` is the returned buffer, result[i] == j means the value at index i
    /// in the element vector belongs to row j of the top-level vector. topLevelRows
    /// must be non-null rows.
    BufferPtr getElementToTopLevelRows(
        vector_size_t numElements,
        const SelectivityVector &topLevelRows,
        const vector_size_t *rawOffsets,
        const vector_size_t *rawSizes,
        const uint64_t *rawNulls,
        memory::MemoryPool *pool);

    template<typename T>
    BufferPtr getElementToTopLevelRows(
        vector_size_t numElements,
        const SelectivityVector &topLevelRows,
        const T *topLevelVector,
        memory::MemoryPool *pool) {
        auto rawNulls = topLevelVector->raw_nulls();
        auto rawSizes = topLevelVector->rawSizes();
        auto rawOffsets = topLevelVector->rawOffsets();

        return getElementToTopLevelRows(
            numElements, topLevelRows, rawOffsets, rawSizes, rawNulls, pool);
    }
} // namespace kumo::pollux::functions
